/**
 * Copyright(c) 2010 Ceno Techonologies Co., Ltd.
 *
 * History:
 *   15-4-20 下午6:20 Created by lyyang
 */
package com.xunton.bss.weixin.api.yaozb;

import java.io.File;
import java.net.URLEncoder;
import java.util.*;
import javax.inject.Inject;
import javax.inject.Named;

import com.jade.framework.base.util.HttpUtils;
import com.xunton.bss.weixin.api.Response;
import com.xunton.bss.weixin.api.token.TokenAgent;
import com.xunton.bss.weixin.api.yaozb.pdu.BeaconInfo;
import com.xunton.bss.weixin.api.yaozb.pdu.PageInfo;
import com.xunton.bss.weixin.api.yaozb.response.*;


/**
 * 摇一摇管理器
 *
 * @author <a href="mailto:lyyang@ceno.cn">lyyang</a>
 * @version 1.0 15-4-20 下午6:20
 */
@Named ("weixin_yaozbAgent")
public class YaozbAgent
{
    private final static String URL_SEARCH_BEACON = "https://api.weixin.qq.com/shakearound/device/search?access_token=";
    private final static String URL_SEARCH_PAGE = "https://api.weixin.qq.com/shakearound/page/search?access_token=";
    private final static String URL_STAT_DEVICE_PAGE = "https://api.weixin.qq.com/shakearound/statistics/device?access_token=";
    private final static String URL_STAT_URL_PAGE = "https://api.weixin.qq.com/shakearound/statistics/page?access_token=";
    private final static String URL_APPLY_BEACON = "https://api.weixin.qq.com/shakearound/device/applyid?access_token=";
    private final static String URL_UPDATE_BEACON = "https://api.weixin.qq.com/shakearound/device/update?access_token=";
    private final static String URL_BEACON_POI = "https://api.weixin.qq.com/shakearound/device/bindlocation?access_token=";
    private final static String URL_UPLOAD_PIC = "https://api.weixin.qq.com/shakearound/material/add?access_token=";
    private final static String URL_CREATE_PAGE = "https://api.weixin.qq.com/shakearound/page/add?access_token=";
    private final static String URL_UPDATE_PAGE = "https://api.weixin.qq.com/shakearound/page/update?access_token=";
    private final static String URL_REMOVE_PAGE = "https://api.weixin.qq.com/shakearound/page/delete?access_token=";
    private final static String URL_BIND_URL = "https://api.weixin.qq.com/shakearound/device/bindpage?access_token=";
    private final static String URL_USER_SHAKE_INFO = "https://api.weixin.qq.com/shakearound/user/getshakeinfo?access_token=";
    private final static String URL_QUERY_APPLY = "https://api.weixin.qq.com/shakearound/device/applystatus?access_token=";
    private TokenAgent tokenAgent;

    public static void main(String[] args)
    {
        YaozbAgent agent = new YaozbAgent();

        try {
//            ApplyBeaconResponse response = manager.applyBeacon(1,"摇周边测试","摇周边测试");
//            System.out.println(response);
//            long deviceId = response.getApplyData().getBeaconInfos().get(0).getDeviceId();
//            Response re = manager.updateBeacon(deviceId,"讯通要周边测试");

//            File file = new File("d:/temp/contact1.jpg");
//            System.out.println(file.exists());
//            UploadIconResponse response = manager.uploadIcon(file);
//
//            System.out.println(response);

//            PageInfo page = new PageInfo();
//            page.setPageId(75788);
//            page.setTitle("章高");
//            page.setDescription("徐小姐");
//            page.setComment("章徐小姐");
//            page.setIconUrl("http://shp.qpic.cn/wx_shake_bus/0/1431066191d03d864b7f43db9ce34df5f720509d0e/120");
//            page.setPageUrl("http://www.zhenai.com");
//            PageDataResponse response = manager.updatePage(page);
//            long[] ids = {75788};
//            Response response = manager.associatePage(625126,ids,true,true);
//            System.out.println(response);
            System.out.println(URLEncoder.encode("http://wx.xunton.com/admin/test/getUserInfo.do", "utf-8"));


        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Inject
    public void setTokenAgent(@Named ("weixin_tokenAgent") TokenAgent tokenAgent)
    {
        this.tokenAgent = tokenAgent;
    }

    public Response bindBeaconToPage(long deviceId, long[] pageIds, boolean bind, boolean append)
            throws Exception
    {
        return bindBeaconToPage(tokenAgent.getAccessToken(), deviceId, pageIds, bind, append);
    }

    public Response bindBeaconToPage(String token, long deviceId, long[] pageIds, boolean bind, boolean append)
            throws Exception
    {
        int intBind = bind ? 1 : 0;
        int intAppend = append ? 1 : 0;
        HashMap params = new HashMap();
        BeaconInfo beacon = new BeaconInfo();
        beacon.setDeviceId(deviceId);
        params.put("device_identifier", beacon);
        params.put("page_ids", pageIds);
        params.put("bind", intBind);
        params.put("append", intAppend);
        Response response = HttpUtils.postJsonHttp(URL_BIND_URL + token, params, Response.class);
        return response;
    }

    public PageDataResponse createPage(PageInfo page)
            throws Exception
    {
        return createPage(tokenAgent.getAccessToken(), page);

    }

    public PageDataResponse createPage(String token, PageInfo page)
            throws Exception
    {
        PageDataResponse response = HttpUtils.postJsonHttp(URL_CREATE_PAGE + token, page, PageDataResponse.class);
        return response;
    }

    public PageDataResponse updatePage(PageInfo page)
            throws Exception
    {
        return updatePage(tokenAgent.getAccessToken(), page);

    }

    public PageDataResponse updatePage(String token, PageInfo page)
            throws Exception
    {
        PageDataResponse response = HttpUtils.postJsonHttp(URL_UPDATE_PAGE + token, page, PageDataResponse.class);
        return response;
    }

    public Response[] deletePage(long[] ids)
            throws Exception
    {
        Response[] responses = new Response[ids.length];
        for (int i = 0; i < ids.length; i++) {
            responses[i] = deletePage(tokenAgent.getAccessToken(), ids[i]);
        }
        return responses;
    }

    public Response deletePage(String token, long id)
            throws Exception
    {
        HashMap params = new HashMap();
        params.put("page_id", id);
        Response response = HttpUtils.postJsonHttp(URL_REMOVE_PAGE + token, params, Response.class);
        return response;
    }

    public UploadIconResponse uploadPageIcon(File file)
            throws Exception
    {
        return uploadPageIcon(tokenAgent.getAccessToken(), file);
    }

    public UploadIconResponse uploadPageIcon(String token, File file)
            throws Exception
    {
        UploadIconResponse response = HttpUtils.postFile(URL_UPLOAD_PIC + token, "media", file,
                UploadIconResponse.class);
        return response;
    }

    public Response bindBeaconToStore(long deviceId, long poiId)
            throws Exception
    {
        return bindBeaconToStore(tokenAgent.getAccessToken(), deviceId, poiId);

    }

    public Response bindBeaconToStore(String token, long deviceId, long poiId)
            throws Exception
    {
        HashMap params = new HashMap();
        BeaconInfo beacon = new BeaconInfo();
        beacon.setDeviceId(deviceId);
        params.put("device_identifier", beacon);
        params.put("poi_id", poiId);
        Response response = HttpUtils.postJsonHttp(URL_BEACON_POI + token, params, Response.class);
        return response;
    }

    public ApplyBeaconResponse applyBeacon(int quantity, String reason, String comment)
            throws Exception
    {
        return applyBeacon(tokenAgent.getAccessToken(), quantity, reason, comment);
    }

    public ApplyBeaconResponse applyBeacon(String token, int quantity, String reason, String comment)
            throws Exception
    {
        HashMap params = new HashMap();
        params.put("quantity", quantity);
        params.put("apply_reason", reason);
        params.put("comment", comment);
        ApplyBeaconResponse response = HttpUtils.postJsonHttp(URL_APPLY_BEACON + token, params,
                ApplyBeaconResponse.class);
        return response;
    }

    public Response updateBeacon(long deviceId, String comment)
            throws Exception
    {
        return updateBeacon(tokenAgent.getAccessToken(), deviceId, comment);

    }

    public Response updateBeacon(String token, long deviceId, String comment)
            throws Exception
    {
        HashMap params = new HashMap();
        BeaconInfo beacon = new BeaconInfo();
        beacon.setDeviceId(deviceId);
        params.put("device_identifier", beacon);
        params.put("comment", comment);
        Response response = HttpUtils.postJsonHttp(URL_UPDATE_BEACON + token, params, Response.class);
        return response;
    }

    public SearchBeaconResponse searchBeacon(long applyId, int offset, int length, long... deviceIds)
            throws Exception
    {
        return searchBeacon(tokenAgent.getAccessToken(), applyId, offset, length, deviceIds);
    }

    public SearchBeaconResponse searchBeacon(String token, long applyId, int offset, int length, long... deviceIds)
            throws Exception
    {
        HashMap params = new HashMap();
        params.put("begin", offset);
        params.put("count", length);
        if (applyId > 0) {
            params.put("apply_id", applyId);
        }
        if (deviceIds != null && deviceIds.length > 0) {
            List<BeaconInfo> infos = new ArrayList<BeaconInfo>();
            for (long deviceId : deviceIds) {
                BeaconInfo info = new BeaconInfo();
                info.setDeviceId(deviceId);
                infos.add(info);
            }
            params.put("device_identifiers", infos);
        }
        SearchBeaconResponse msgSearch = HttpUtils.postJsonHttp(URL_SEARCH_BEACON + token, params,
                SearchBeaconResponse.class);
        return msgSearch;


    }

    public SearchPageResponse searchPage(int offset, int length, long... pageIds)
            throws Exception
    {
        return searchPage(tokenAgent.getAccessToken(), offset, length, pageIds);
    }

    public SearchPageResponse searchPage(String token, int offset, int length, long... pageIds)
            throws Exception
    {
        HashMap params = new HashMap();
        params.put("begin", offset);
        params.put("count", length);
        if (pageIds != null && pageIds.length > 0) {
            List<Long> pages = new ArrayList<Long>();
            for (long pageId : pageIds) {
                pages.add(pageId);
            }
            params.put("page_ids", pages);
        }
        SearchPageResponse msg = HttpUtils.postJsonHttp(URL_SEARCH_PAGE + token, params, SearchPageResponse.class);
        return msg;


    }

    public StatResponse statBeacon(long deviceId, Date start, Date end)
            throws Exception
    {
        return statBeacon(tokenAgent.getAccessToken(), deviceId, start, end);
    }

    public StatResponse statBeacon(String token, long deviceId, Date start, Date end)
            throws Exception
    {
        if (end == null) {
            end = new Date();
        }
        if (start == null) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -10);
            start = calendar.getTime();
        }
        BeaconInfo info = new BeaconInfo();
        info.setDeviceId(deviceId);
        HashMap params = new HashMap();
        params.put("begin_date", start.getTime() / 1000);
        params.put("end_date", end.getTime() / 1000);
        params.put("device_identifier", info);
        StatResponse msg = HttpUtils.postJsonHttp(URL_STAT_DEVICE_PAGE + token, params, StatResponse.class);
        return msg;


    }

    public StatResponse statPage(long pageId, Date start, Date end)
            throws Exception
    {
        return statPage(tokenAgent.getAccessToken(), pageId, start, end);
    }

    public StatResponse statPage(String token, long pageId, Date start, Date end)
            throws Exception
    {
        if (end == null) {
            end = new Date();
        }
        if (start == null) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -29);
            start = calendar.getTime();
        }
        HashMap params = new HashMap();

        params.put("begin_date", start.getTime() / 1000);
        params.put("end_date", end.getTime() / 1000);
        params.put("page_id", pageId);
        StatResponse msg = HttpUtils.postJsonHttp(URL_STAT_URL_PAGE + token, params, StatResponse.class);
        return msg;
    }

    public UserInfoResponse getUserInfoFromUrlTicket(String token, String ticket)
            throws Exception
    {
        HashMap params = new HashMap();
        params.put("ticket", ticket);
        params.put("need_poi", 1);
        UserInfoResponse response = HttpUtils.postJsonHttp(URL_USER_SHAKE_INFO + token, params, UserInfoResponse.class);
        return response;
    }

    public UserInfoResponse getUserInfoFromUrlTicket(String ticket)
            throws Exception
    {
        HashMap params = new HashMap();
        params.put("ticket", ticket);
        params.put("need_poi", 1);
        String token = tokenAgent.getAccessToken();
        UserInfoResponse response = HttpUtils.postJsonHttp(URL_USER_SHAKE_INFO + token, params, UserInfoResponse.class);
        return response;
    }

    public QueryApplyResponse queryApply(String token, long applyId)
            throws Exception
    {
        HashMap params = new HashMap();
        params.put("apply_id", applyId);
        QueryApplyResponse response = HttpUtils.postJsonHttp(URL_QUERY_APPLY + token, params, QueryApplyResponse.class);
        return response;
    }

    public QueryApplyResponse queryApply(long applyId)
            throws Exception
    {
        return queryApply(tokenAgent.getAccessToken(), applyId);
    }
}
